/*
Copyright (C) Ariff Ehsan, Abdul Hadi Fikri

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

/*  Author : Ariff Ehsan
 *  Date   : June 18, 2009
 */


#include <system.h>


void (*attiny85_timer0_fired)(void);	


void ATTINY85_TIMER0_defaultFired(void);


void ATTINY85_TIMER0_init(void) {

#if DEBUGGING==ENABLE
	SET_BIT(CLOCK_PULSE_DIR, CLOCK_PULSE_PIN);
	CLR_BIT(CLOCK_PULSE_PORT, CLOCK_PULSE_PIN);
#endif

	// set default fired pointer
	attiny85_timer0_fired = ATTINY85_TIMER0_defaultFired;
	
	// set CTC mode and prescaller 4
	TCCR0A = (1<<WGM01);
	TCCR0B = (1<<CS01)|(1<<CS00);
	
	TCNT0 = 0;
	
	// set timer count for 1 milli seconds
	OCR0A = 125;
	
	// enable output compare 0 interrupt
	TIMSK |= (1<<OCIE0A);
}

void ATTINY85_TIMER0_reg(void (*fired)(void)) {
	if (fired != NULL)
		attiny85_timer0_fired = fired;
}


void ATTINY85_TIMER0_defaultFired(void) {
}


ISR(TIM0_COMPA_vect) {
#if DEBUGGING==ENABLE
	FLIP_BIT(CLOCK_PULSE_PORT, CLOCK_PULSE_PIN);
#endif

	(*attiny85_timer0_fired)();
}
